<template>
  <Dialog :appDialog="appDialog">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <!-- 分组 -->
      <el-form-item label="分组">
        <el-cascader
          v-model="form.group"
          :options="groupData"
          :show-all-levels="false"
          :props="defaultProps"
          placeholder="请选择分组"
        />
      </el-form-item>
      <!-- 标题 -->
      <template>
        <el-form-item label="标题">
          <el-input
            v-model="form.title"
            maxlength="12"
            show-word-limit
            :placeholder="`请输入${labelName[type]}标题`"
          ></el-input>
        </el-form-item>
      </template>
      <!-- 类型 -->
      <template v-if="[2, 4, 5].includes(type)">
        <el-form-item label="类型">
          <el-radio-group v-model="form.type" class="radio_list">
            <el-radio
              v-for="item in typeDiff(type)"
              :key="item.value"
              :label="item.value"
              class="radio_list_item"
            >
              <span class="radio_list_item_text">{{ item.name }}</span>
              <el-tooltip
                v-if="item.value === 1"
                :content="item.text"
                placement="bottom"
                effect="light"
              >
                <div class="radio_list_item_icon radio_img">
                  <img src="@/assets/image/material/question.png" alt="" />
                </div>
              </el-tooltip>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </template>

      <template v-if="type == 7"></template>
      <!-- 链接地址 -->
      <template v-if="type == 7">
        <el-form-item label="链接地址">
          <el-input type="text" v-model="form.link"></el-input>
        </el-form-item>
        <!-- 连接描述 -->
        <el-form-item label="链接描述">
          <el-input
            type="texteare"
            v-model="form.linkDesc"
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>
      </template>
      <!-- 上传文件 -->
      <ZWUpload :upInfo="upLoadType[type]" />
      <!-- 标签 -->
      <el-form-item label="标签">
        <el-scrollbar v-if="form.tags.length > 0" max-height="100px">
          <el-tag
            class="mr10"
            v-for="tag in form.tags"
            :key="tag.id"
            plain
            closable
            :disable-transitions="false"
            @close="handleClose(tag.id)"
          >
            {{ tag.name }}
          </el-tag>
        </el-scrollbar>
        <el-button type="primary" plain @click="openTag" size="small"
          >请选择标签</el-button
        >
      </el-form-item>
      <el-form-item label="">
        <div class="agree_ment">
          <el-checkbox v-model="form.check"></el-checkbox>
          <span class="ml2">勾选代表同意</span>
          <el-link class="form-link" type="primary" :underline="false"
            >《***用户协议》</el-link
          >
        </div>
      </el-form-item>
    </el-form>
  </Dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import Dialog from "@/components/Dialog.vue";
import ZWUpload from "@/components/ZWUpload.vue";
import { ElForm } from "element-plus";
import { uploadBaseMaterial , updateBaseMaterial , getBaseMaterialDetail, getFileInfo, updateFile} from "@/api/concreation";
import bus from '@/utils/bus'
const formRef = ref<InstanceType<typeof ElForm>>();
const emit = defineEmits(["submit"]);
import { useStore } from "@/store";
const store = useStore();

const uploadTitle = ref("上传文件");
const uploadVisib = ref(false);
const isEdit = ref(false)
const editType = ref(0)
// 1-文本 2-图片 3-音频 4-视频 5-文件 6-链接文章 7-链接引用
const type = computed(() => {
  return store.getters["content/type"];
});
//上传弹框
const uploadInfo = computed(() => {
  return store.getters["content/upload"];
});
// 分组列表
const group = computed(() => {
  return store.getters["content/group"];
});
//标签
const tags = computed(() => {
  return store.getters["content/tagsInfo"].tags;
});
const defaultProps = {
  checkStrictly: true,
  emitPath: false,
  label: "name",
  value: "id",
};
// 分组 tree
const groupData = ref([
  {
    id: 0,
    name: "全部分组",
    children: [
      {
        id: 1,
        name: "默认分组",
        children: [
          {
            id: 2,
            name: "分组1",
          },
        ],
      },
    ],
  },
]);
const form = reactive({
  group: "", //分组
  type: 0,
  images: [], // 图片
  video: "", // 音频文件
  audio: "", // 视频文件
  files: "", //文件
  tags: [], //标签
  check: true, //用户协议
  title: "", //标题
  link: "", //链接地址
  linkDesc: "", // 连接描述
  id: "",//内容id
});

const rules = reactive({
  images: [
    {
      required: true,
      message: "图片不能为空",
      trigger: "click",
    },
  ],
  video: [
    {
      required: true,
      message: "视频不能为空",
      trigger: "click",
    },
  ],
  files: [
    {
      required: true,
      message: "文件不能为空",
      trigger: "click",
    },
  ],
  audio: [
    {
      required: true,
      message: "语音不能为空",
      trigger: "click",
    },
  ],
});
// 图片上传
const picInfo = reactive({
  type: 1,
  label: "图片",
  prop: "images",
  files: form.images,
  multiple: true,
  limitSize: 2,
  limitNum: 9,
  acceptFile: ".jpg,.jpeg,.png,.gif,.bmp,.webp",
});
// 文件上传
const fileInfo = reactive({
  type: 2,
  label: "文件",
  prop: "files",
  files: form.files,
  multiple: false,
  limitSize: 20,
  limitNum: 1,
  acceptFile: ".DOC,.DOCX,.XLS,.XLSX,.CSV,.PPT,.PPTX,.TXT,.PDF,.Xmind",
});
// 视频上传
const videoInfo = reactive({
  type: 3,
  label: "视频",
  prop: "video",
  files: form.video,
  multiple: false,
  limitSize: 10,
  acceptFile: ".mp4",
});
// 语音上传
const audioInfo = reactive({
  type: 4,
  label: "语音",
  prop: "audio",
  files: form.audio,
  multiple: false,
  limitSize: 200,
  acceptFile: ".mp3,.wma,.wav,.amr,.m4a",
});
const labelName = reactive(["", "", "图片", "", "视频", "文件"]);
const upLoadType = reactive([
  "",
  "",
  picInfo,
  videoInfo,
  audioInfo,
  fileInfo,
  "",
  fileInfo,
]);

const typeDiff = (type: number) => {
  return [
    { value: 0, name: `普通${labelName[type]}` },
    {
      value: 1,
      name: `雷达${labelName[type]}`,
      text: `雷达${labelName[type]}可以追踪客户端浏览次数、时间等数据`,
    },
  ];
};
// 取消
const cancelHandel = () => {
  appDialog.visible = false;
  formRef.value.resetFields();
};
//确定
const submitHandel = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      try {
        let arr: any[] = [];
        form.tags.forEach((item: any) => {
          arr.push(item.id);
        });
        if(isEdit.value){
          if(editType.value == 5){
            let tag_ids:any = [];
            form.tags.forEach((item:any) => {
              tag_ids.push(item.id)
            })
            updateFile({
              title: form.title,
              group_id: form.group,
              file_type: form.type,
              code: '',
              tag_ids: tag_ids,
              media_content_id: form.id
            }).then((data:any) => {
              console.log(data);
              //修改成功
            })
          }
          // updateBaseMaterial({
          //   type: type.value,
          //   title: form.title,
          //   content_id: form.id
          // }).the((res:any) => {
          //   console.log(res);
          // })
        }else{
          uploadBaseMaterial({
            type: type.value,
            title: form.title,
            tag_ids: arr,
          }).then((res: any) => {
            emit("submit");
            cancelHandel();
          });
        }
      } catch (e) {
        console.log(e);
      }
    }
  });
};
const appDialog = reactive({
  visible: uploadVisib,
  title: uploadTitle,
  width: "670px",
  cancel: cancelHandel,
  submit: submitHandel,
  cancelText: "取消",
  submitText: "保存",
});
//获取编辑内容
const editItem = (data:any) => {
  const params = {
    media_content_id:data.media_content_id
  }
  if(data.type == 5){
    editType.value = 5
    //获取文件详情
    getFileInfo(params).then((data:any) => {
      isEdit.value = true
      form.title = data.title;
      form.group = data.group_id;
      form.tags = data.tagInfo;
      form.type = data.is_radar;
      form.id = data.id;
    })
  }
}
bus.on('editItem', editItem)
watch(uploadInfo,
  (uploadInfo) => {
    console.log(uploadInfo, "====uploadInfo");
    uploadTitle.value = uploadInfo.title;
    uploadVisib.value = uploadInfo.uploadVisib;
  }
);
watch(group, (data) => {
  console.log(data,'------grop2');
  groupData.value = data.groupList;
});
watch(tags, (data) => {
  form.tags = data;
});
const openTag = () => {
  store.dispatch("content/tagsInfo", {
    tags: form.tags,
    TagsVisble: true,
  });
};
// 删除标签
const handleClose = (tag: string) => {
  form.tags = form.tags.filter((item: any) => item.id != tag);
  store.dispatch("content/tagsInfo", {
    tags: form.tags,
  });
};
</script>
<style lang="scss" scoped>
.radio_list {
  &_item {
    &_icon {
      width: 14px;
      height: 14px;
      margin: -3px 0 0 6px;
      img {
        margin-top: 2px;
        width: 100%;
        height: 100%;
        vertical-align: top;
      }
    }
  }
  :deep .el-radio__label {
    display: flex;
    align-items: center;
  }
}
.ml2 {
  margin-left: 2px;
}
.mr10 {
  margin-right: 10px;
}
.agree_ment {
  display: flex;
  align-items: center;
}
:deep .el-scrollbar{
  height: 50%;
}
</style>
